package cn.hl.hm.util;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Response返回工具类
 * @author 大和
 *
 */
public class Result {
	private static Logger logger = Logger.getLogger(Result.class);
	public static void writeJSONObject(HttpServletResponse response,JSONObject jsonObject) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(jsonObject);
			out.flush();
			out.close();
			logger.info(jsonObject.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void writeJSONArray(HttpServletResponse response,JSONArray jsonArray) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(jsonArray.toString());
			out.flush();
			out.close();
			logger.info(jsonArray.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void  writeString(HttpServletResponse response,String text) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(text);
			out.flush();
			out.close();
			logger.info("text"+text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void writeJSONOString(HttpServletResponse response,Map<String, Object> json) {
		try {
			response.setContentType("text/html;charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(JacksonJsonUtil.beanToJson(json));
			out.flush();
			out.close();
			logger.info(json.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * @param data 数据
	 * @param code 状态码
	 * @param response
	 */
	public static void ok(Object data, InfoCode InfoCode, HttpServletResponse response) {
		Map<String, Object> relust = new HashMap<String, Object>();
		try {
			relust.put("data", data);
			Map<String, Object> state = new HashMap<String, Object>();
			state.put("stateCode", InfoCode.getStatus());
			state.put("stateMessage", InfoCode.getMsg());
			relust.put("state", state);
			writeJSONOString(response, relust);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("result方法中抛出异常" + e);
		}
	}

}
